package org.jeecg.modules.marketingDepartment.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.faultStatistics.entity.SyFaultHandling;
import org.jeecg.modules.faultStatistics.mapper.SyFaultHandlingMapper;
import org.jeecg.modules.heavyGames.mapper.SyHeavyGamesMapper;
import org.jeecg.modules.heavyLiveStreaming.mapper.SyHeavyLiveStreamingMapper;
import org.jeecg.modules.marketingDepartment.entity.SyMarketingDepartment;
import org.jeecg.modules.marketingDepartment.mapper.SyMarketingDepartmentMapper;
import org.jeecg.modules.marketingDepartment.service.ISyMarketingDepartmentService;
import org.jeecg.modules.marketingDepartment.vo.CartogramVo;
import org.jeecg.modules.terminalMarket.entity.SyTerminalMarket;
import org.jeecg.modules.terminalMarket.service.ISyTerminalMarketService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description: 市场部数据表
 * @Author: jeecg-boot
 * @Date:   2023-10-11
 * @Version: V1.0
 */
@Api(tags="市场部数据表")
@RestController
@RequestMapping("/syMarketingDepartment")
@Slf4j
public class SyMarketingDepartmentController extends JeecgController<SyMarketingDepartment, ISyMarketingDepartmentService> {
	@Autowired
	private ISyMarketingDepartmentService syMarketingDepartmentService;
	@Autowired
	private SyMarketingDepartmentMapper syMarketingDepartmentMapper;
	@Autowired
	private SyFaultHandlingMapper syFaultHandlingMapper;
	@Autowired
	private ISyTerminalMarketService syTerminalMarketService;


	@Autowired
	private SyHeavyGamesMapper heavyGamesMapper;
	@Autowired
	private SyHeavyLiveStreamingMapper heavyLiveStreamingMapper;


	/**
	 * 用户端网不匹配(是质差的用户)
	 */
	@ApiOperation(value="市场部数据表-用户端网不匹配", notes="市场部数据表-用户端网不匹配")
	@GetMapping(value = "/dwbppList")
	public Result<IPage<SyMarketingDepartment>> dwbppList(SyMarketingDepartment syMarketingDepartment,
														 @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
														 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
														 HttpServletRequest req) {
		//QueryWrapper<SyMarketingDepartment> queryWrapper = QueryGenerator.initQueryWrapper(syMarketingDepartment, req.getParameterMap());
		Page<SyMarketingDepartment> page = new Page<SyMarketingDepartment>(pageNo, pageSize);
		//IPage<SyMarketingDepartment> pageList = syMarketingDepartmentService.page(page, queryWrapper.<SyMarketingDepartment>lambda().eq(SyMarketingDepartment::getSfdwbpp,"1"))
		Page<SyMarketingDepartment> syMarketingDepartmentPage = syMarketingDepartmentMapper.selectPage(page, Wrappers.<SyMarketingDepartment>lambdaQuery()
				.eq(SyMarketingDepartment::getSfdwbpp, "1"));
		return Result.OK(syMarketingDepartmentPage);
	}


	/**
	 * 用户端网不匹配
	 */
	@ApiOperation(value="市场部数据表-用户质差统计图", notes="市场部数据表-用户质差统计图")
	@GetMapping(value = "/dwbppCartogram")
	public Result<List<CartogramVo>> dwbppCartogram() {

		List<CartogramVo> cartogramVos =  syMarketingDepartmentMapper.dwbppCartogram();

		List<CartogramVo> cartogramVoList = new ArrayList<>();

		cartogramVos.forEach(s-> {
			if (Objects.equals(s.getName(), "1")){
				s.setName("是");
			}else {
				s.setName("否");
			}
			cartogramVoList.add(s);
		});
		return Result.OK(cartogramVoList);
	}

	/**
	 * 用户质差用户信息(是质差的用户)
	 */
	@ApiOperation(value="市场部数据表-用户质差用户信息(是质差的用户)", notes="市场部数据表-用户质差用户信息(是质差的用户)")
	@GetMapping(value = "/sfzxList")
	public Result<IPage<SyMarketingDepartment>> sfzxList(SyMarketingDepartment syMarketingDepartment,
															 @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
															 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
															 HttpServletRequest req) {
//		syMarketingDepartment.setSfzc("1");
//		QueryWrapper<SyMarketingDepartment> queryWrapper = QueryGenerator.initQueryWrapper(syMarketingDepartment, req.getParameterMap());
		Page<SyMarketingDepartment> page = new Page<SyMarketingDepartment>(pageNo, pageSize);
//		IPage<SyMarketingDepartment> pageList = syMarketingDepartmentService.page(page, queryWrapper);
		Page<SyMarketingDepartment> syMarketingDepartmentPage = syMarketingDepartmentMapper.selectPage(page, Wrappers.<SyMarketingDepartment>lambdaQuery()
				.eq(SyMarketingDepartment::getSfzc, "1"));

		return Result.OK(syMarketingDepartmentPage);
	}



	/**
	 * 用户质差统计图
	 */
	@ApiOperation(value="市场部数据表-用户质差统计图", notes="市场部数据表-用户质差统计图")
	@GetMapping(value = "/sfzxCartogram")
	public Result<List<CartogramVo>> sfzxCartogram() {

		List<CartogramVo> cartogramVoList =  syFaultHandlingMapper.sfzxCartogram();

		List<CartogramVo> cartogramVos = new ArrayList<>();

		cartogramVoList.forEach(s->{
			if (Objects.equals(s.getName(), "1")){
				s.setName("是");
			}else {
				s.setName("否");
			}
			cartogramVos.add(s);
		});
		return Result.OK(cartogramVos);
	}

	/**
	 * 用户幸好统计图
	 */
	@ApiOperation(value="市场部数据表-用户幸好统计图", notes="市场部数据表-用户幸好统计图")
	@GetMapping(value = "/subscriberSignal")
	public Result<List<CartogramVo>> subscriberSignal(){
		List<CartogramVo> cartogramVos = new ArrayList<>();

		//重度游戏
		CartogramVo cartogramVoGames = new CartogramVo();
		int sizeGames = heavyGamesMapper.selectList(null).size();
		cartogramVoGames.setName("重度游戏用户");
		cartogramVoGames.setAmount(sizeGames);
		cartogramVos.add(cartogramVoGames);
		//重度直播
		CartogramVo cartogramVoLiveStreaming = new CartogramVo();
		int sizeLiveStreaming = heavyLiveStreamingMapper.selectList(null).size();
		cartogramVoLiveStreaming.setName("重度直播用户");
		cartogramVoLiveStreaming.setAmount(sizeLiveStreaming);
		cartogramVos.add(cartogramVoLiveStreaming);
		return Result.OK(cartogramVos);
	}





	/**
	 * 首页欠费更多接口
	 * @param syMarketingDepartment
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@ApiOperation(value="市场部数据表-首页欠费更多接口", notes="市场部数据表-首页欠费更多接口")
	@GetMapping(value = "/moreDebtList")
	public Result<IPage<SyMarketingDepartment>> moreDebtList(SyMarketingDepartment syMarketingDepartment,
														 @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
														 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
														 HttpServletRequest req) {
		QueryWrapper<SyMarketingDepartment> queryWrapper = QueryGenerator.initQueryWrapper(syMarketingDepartment, req.getParameterMap());
		Page<SyMarketingDepartment> page = new Page<SyMarketingDepartment>(pageNo, pageSize);

		//查询出欠费不为null的并且按最大的排序
		IPage<SyMarketingDepartment> pageList = syMarketingDepartmentService.page(page, queryWrapper.lambda()
				.isNotNull(SyMarketingDepartment::getAmountInArrear));



		return Result.OK(pageList);
	}

	/**
	 * 首页欠费前10展示
	 * @param syMarketingDepartment
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@ApiOperation(value="市场部数据表-首页欠费前10展示", notes="市场部数据表-首页欠费前10展示")
	@GetMapping(value = "/debtList")
	public Result<List<SyMarketingDepartment>> debtList(SyMarketingDepartment syMarketingDepartment,
															  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
															  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
															  HttpServletRequest req) {
//		QueryWrapper<SyMarketingDepartment> queryWrapper = QueryGenerator.initQueryWrapper(syMarketingDepartment, req.getParameterMap());
//		Page<SyMarketingDepartment> page = new Page<SyMarketingDepartment>(pageNo, pageSize);

		//查询出欠费不为null的并且按最大的排序
//		IPage<SyMarketingDepartment> pageList = syMarketingDepartmentService.page(page, queryWrapper.lambda()
//				.isNotNull(SyMarketingDepartment::getAmountInArrear).orderByDesc(SyMarketingDepartment::getAmountInArrear));

		List<SyMarketingDepartment> syMarketingDepartments =  syMarketingDepartmentMapper.debtList();
		return Result.OK(syMarketingDepartments);
	}







	//----------------------------------------------新添加接口--------------------------------------------

	/**
	 * 分页列表查询
	 *
	 * @param syMarketingDepartment
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "市场部数据表-分页列表查询")
	@ApiOperation(value="市场部数据表-分页列表查询", notes="市场部数据表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<SyMarketingDepartment>> queryPageList(SyMarketingDepartment syMarketingDepartment,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<SyMarketingDepartment> queryWrapper = QueryGenerator.initQueryWrapper(syMarketingDepartment, req.getParameterMap());
		Page<SyMarketingDepartment> page = new Page<SyMarketingDepartment>(pageNo, pageSize);
		IPage<SyMarketingDepartment> pageList = syMarketingDepartmentService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param syMarketingDepartment
	 * @return
	 */
	@AutoLog(value = "市场部数据表-添加")
	@ApiOperation(value="市场部数据表-添加", notes="市场部数据表-添加")
	//@RequiresPermissions("add3:sy_marketing_department:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody SyMarketingDepartment syMarketingDepartment) {

//		if (Objects.equals(syMarketingDepartment.getAmountInArrear(), "")){
//			syMarketingDepartment.setAmountInArrear(null);
//		}
		syMarketingDepartmentService.save(syMarketingDepartment);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param syMarketingDepartment
	 * @return
	 */
	@AutoLog(value = "市场部数据表-编辑")
	@ApiOperation(value="市场部数据表-编辑", notes="市场部数据表-编辑")
	//@RequiresPermissions("add3:sy_marketing_department:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody SyMarketingDepartment syMarketingDepartment) {
		SyMarketingDepartment selectOnes = syMarketingDepartmentMapper.selectOne(Wrappers.<SyMarketingDepartment>lambdaQuery()
				.eq(SyMarketingDepartment::getId, syMarketingDepartment.getId()));

		//1、是否千兆光猫

		//2、是否终端硬合约
		if (!Objects.equals(selectOnes.getMainMealName(), syMarketingDepartment.getMainMealName())){
			SyTerminalMarket syTerminalMarket = syTerminalMarketService.getOne(Wrappers.<SyTerminalMarket>lambdaQuery().eq(SyTerminalMarket::getXspggmc, syMarketingDepartment.getMainMealName()));
			if (syTerminalMarket != null){
				syMarketingDepartment.setSfzdyhy("1");
			}else {
				syMarketingDepartment.setSfzdyhy("0");
			}
		}

		//3、是否质差
		if (!Objects.equals(selectOnes.getKdxxsl(), syMarketingDepartment.getKdxxsl()) || !Objects.equals(selectOnes.getTerminalRate(), syMarketingDepartment.getTerminalRate())){
			if (syMarketingDepartment.getTerminalRate() > syMarketingDepartment.getKdxxsl()){
				syMarketingDepartment.setSfzc("1");
			}else {
				syMarketingDepartment.setSfzc("0");
			}
		}

		//5、是否端网不匹配
		if (!Objects.equals(selectOnes.getKdxxsl(), syMarketingDepartment.getKdxxsl()) || !Objects.equals(selectOnes.getTerminalRate(), syMarketingDepartment.getTerminalRate())){
			if (syMarketingDepartment.getTerminalRate() < syMarketingDepartment.getKdxxsl()){
				syMarketingDepartment.setSfdwbpp("1");
			}else {
				syMarketingDepartment.setSfdwbpp("0");
			}
		}

		//7、是否近三个月障碍

		//8、是否中高值
		if (!Objects.equals(selectOnes.getMainMealName(), syMarketingDepartment.getMainMealName())){
			//截取价格
			String str = syMarketingDepartment.getMainMealName().split("元")[0];
			String num = "";
			int length = str.length();
			while (length-- > 0) {
				char c = str.charAt(length);
				if (Character.isDigit(c)) {
					num=c+num;
				}else {
					break;
				}
			}
			int numTme = Integer.parseInt(num);

			String jsgyzhpjczsr = syMarketingDepartment.getJsgyzhpjczsr();
			double numT = Double.parseDouble(jsgyzhpjczsr);
			Long resultT = Math.round(numT);

			//套餐价值大于等于99+近三月账户下平均出账收入(分摊前)大于等于129）
			if (numTme >= 99 && resultT >= 129){
				syMarketingDepartment.setSfzgz("1");
			}else {
				syMarketingDepartment.setSfzgz("0");
			}
		}

		syMarketingDepartmentService.updateById(syMarketingDepartment);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "市场部数据表-通过id删除")
	@ApiOperation(value="市场部数据表-通过id删除", notes="市场部数据表-通过id删除")
	//@RequiresPermissions("add3:sy_marketing_department:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		syMarketingDepartmentService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "市场部数据表-批量删除")
	@ApiOperation(value="市场部数据表-批量删除", notes="市场部数据表-批量删除")
	//@RequiresPermissions("add3:sy_marketing_department:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.syMarketingDepartmentService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "市场部数据表-通过id查询")
	@ApiOperation(value="市场部数据表-通过id查询", notes="市场部数据表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<SyMarketingDepartment> queryById(@RequestParam(name="id",required=true) String id) {
		SyMarketingDepartment syMarketingDepartment = syMarketingDepartmentService.getById(id);
		if(syMarketingDepartment==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(syMarketingDepartment);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param syMarketingDepartment
    */
   // @RequiresPermissions("add3:sy_marketing_department:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, SyMarketingDepartment syMarketingDepartment) {
        return super.exportXls(request, syMarketingDepartment, SyMarketingDepartment.class, "市场部数据表");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("add3:sy_marketing_department:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		Result<?> result = super.importExcel(request, response, SyMarketingDepartment.class);

		//进行自动计算
		//1、是否千兆光猫


		//2、是否终端硬合约
		List<SyMarketingDepartment> mainMealNames = syMarketingDepartmentService.list(Wrappers.<SyMarketingDepartment>lambdaQuery()
				.isNull(SyMarketingDepartment::getSfzdyhy));
		mainMealNames.forEach(m->{
			SyTerminalMarket syTerminalMarket = syTerminalMarketService.getOne(Wrappers.<SyTerminalMarket>lambdaQuery()
					.eq(SyTerminalMarket::getXspggmc, m.getMainMealName()));
			if (syTerminalMarket != null){
				m.setSfzdyhy("1");
				syMarketingDepartmentService.updateById(m);
			}else {
				m.setSfzdyhy("0");
				syMarketingDepartmentService.updateById(m);
			}
		});

		//3、是否质差
		List<SyMarketingDepartment> sfzcS = syMarketingDepartmentService.list(Wrappers.<SyMarketingDepartment>lambdaQuery()
				.isNull(SyMarketingDepartment::getSfzc));
		sfzcS.forEach(s->{
			if (s.getTerminalRate()  > s.getKdxxsl()){
				s.setSfzc("1");
				syMarketingDepartmentService.updateById(s);
			}else {
				s.setSfzc("0");
				syMarketingDepartmentService.updateById(s);
			}
		});

		//5、是否端网不匹配
		List<SyMarketingDepartment> sfdwbppS = syMarketingDepartmentService.list(Wrappers.<SyMarketingDepartment>lambdaQuery()
				.isNull(SyMarketingDepartment::getSfdwbpp));
		sfdwbppS.forEach(i->{
			if (i.getTerminalRate() < i.getKdxxsl()){
				i.setSfdwbpp("1");
				syMarketingDepartmentService.updateById(i);
			}else {
				i.setSfdwbpp("0");
				syMarketingDepartmentService.updateById(i);
			}
		});

		//7、是否近三个月障碍
		List<SyMarketingDepartment> jsgyzhpjczsrS = syMarketingDepartmentService.list(Wrappers.<SyMarketingDepartment>lambdaQuery()
				.isNull(SyMarketingDepartment::getSfjsgyzi));
		jsgyzhpjczsrS.forEach(j->{
			//查询前3个月
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
			Date date = new Date();
			Date threeMonthsAgo = new Date(date.getTime() - 3 * 30 * 24 * 60 * 60 * 1000);
			//前3个月
			String nowStr = formatter.format(threeMonthsAgo);
			//创建时间
			String format = formatter.format(j.getCreateTime());
			List<SyFaultHandling> syFaultHandlings = syFaultHandlingMapper.selectTime(nowStr,format,j.getUsername());
			if (syFaultHandlings.size() != 0){
				j.setSfjsgyzi("1");
				syMarketingDepartmentService.updateById(j);
			}else {
				j.setSfjsgyzi("0");
				syMarketingDepartmentService.updateById(j);
			}
		});

		//8、是否中高值
		List<SyMarketingDepartment> sfzgzS = syMarketingDepartmentService.list(Wrappers.<SyMarketingDepartment>lambdaQuery()
				.isNull(SyMarketingDepartment::getSfzgz));
		sfzgzS.forEach(z->{
			if (z.getMainMealName() != null){
				//截取价格
				String str = z.getMainMealName().split("元")[0];
				String num = "";
				int length = str.length();
				while (length-- > 0) {
					char c = str.charAt(length);
					if (Character.isDigit(c)) {
						num=c+num;
					}else {
						break;
					}
				}
				int numTme = Integer.parseInt(num);

				String jsgyzhpjczsr = z.getJsgyzhpjczsr();
				double numT = Double.parseDouble(jsgyzhpjczsr);
				Long resultT = Math.round(numT);

				//套餐价值大于等于99+近三月账户下平均出账收入(分摊前)大于等于129）
				if (numTme >= 99 && resultT >= 129){
					z.setSfzgz("1");
					syMarketingDepartmentService.updateById(z);
				}else {
					z.setSfzgz("0");
					syMarketingDepartmentService.updateById(z);
				}
			}
		});

		return result;
    }

}
